package completablefuture;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;

/**
 * applyToEither()方法：谁先完成，就用谁的结果继续执行后续操作。
 */
public class Test4 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            int number = new Random().nextInt(10);
            System.out.println("future1 start：" + number);
            MyUtil.sleep(number);
            System.out.println("future1 end：" + number);
            return number;
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            int number = new Random().nextInt(10);
            System.out.println("future2 start：" + number);
            MyUtil.sleep(number);
            System.out.println("future2 end：" + number);
            return number;
        });
        CompletableFuture<Integer> future = future1.applyToEither(future2, new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer number) {
                System.out.println("最快结果：" + number);
                return number;
            }
        });
        Integer result = future.get();
        System.out.println("结果值为 " + result);
    }
}
